package com.runlooker.runer.ui.home.contact;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.runlooker.runer.R;
import com.runlooker.runer.application.MyApplication;
import com.runlooker.runer.dao.RosterEntryDao;
import com.runlooker.runer.entity.LocalRosterEntity;
import com.runlooker.runer.interfaces.RosterChangeListener;
import com.runlooker.runer.service.XmppService;
import com.runlooker.runer.ui.base.BaseFragement;
import com.runlooker.runer.ui.home.HomeActivty;
import com.runlooker.runer.ui.home.contact.SideBar.OnTouchingLetterChangedListener;
import com.runlooker.runer.util.JidUtil;

public class ContactFragment extends BaseFragement implements
		RosterChangeListener {
	public static final String ROSTER_CHANGE_ACTION = "roster_change_action";// 删除好友
	private static final String tag = ContactFragment.class.getSimpleName();
	private ListView sortListView;
	private SideBar sideBar;
	private TextView dialog;
	private SortAdapter adapter;
	private RosterEntryDao mRosterEntryDao;

	private Handler mHandler = new Handler();

	/**
	 * 汉字转换成拼音的类
	 */
	private CharacterParser mCharacterParser = CharacterParser.getInstance();;
	private List<SortModel> SourceDateList;

	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparator pinyinComparator;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View newsLayout = inflater.inflate(R.layout.fragment_contact,
				container, false);
		mRosterEntryDao = new RosterEntryDao(getActivity());
		return newsLayout;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);
		initViews(view);
		refreshUI();
		XmppService.addRosterChangelistener(this);
	}

	private void initViews(View view) {
		sideBar = (SideBar) view.findViewById(R.id.sidrbar);
		dialog = (TextView) view.findViewById(R.id.dialog);
		sideBar.setTextView(dialog);

		// 设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {
			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				int position = adapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					sortListView.setSelection(position);
				}
			}
		});
		sortListView = (ListView) view.findViewById(R.id.country_lvcountry);
	}

	/**
	 * 从本地数据抓取数据并刷新UI
	 */
	private void refreshUI() {

		SourceDateList = filledData(mRosterEntryDao.getMySubscription());
		pinyinComparator = new PinyinComparator();
		// 根据a-z进行排序源数据
		if (!(SourceDateList == null) && !SourceDateList.isEmpty()) {
			Collections.sort(SourceDateList, pinyinComparator);
		}
		adapter = new SortAdapter(getActivity(), SourceDateList);
		sortListView.setAdapter(adapter);
	}

	/**
	 * 为ListView填充数据
	 * 
	 * @param date
	 * @return
	 */
	private List<SortModel> filledData(List<LocalRosterEntity> contaList) {
		List<SortModel> mSortList = new ArrayList<SortModel>();
		if (contaList != null && !contaList.isEmpty()) {
			for (int i = 0; i < contaList.size(); i++) {
				if (!MyApplication.isSelf(getActivity(), contaList.get(i)
						.getAccount())) {
					SortModel sortModel = new SortModel();
					sortModel.setName(contaList.get(i).getName());
					sortModel.setAccount(JidUtil.getAccountFromJID(contaList
							.get(i).getAccount()));
					// 汉字转换成拼音
					String pinyin = mCharacterParser.getSelling(contaList
							.get(i).getName() == null ? "runer" : contaList
							.get(i).getName());
					String sortString = pinyin.substring(0, 1).toUpperCase();

					// 正则表达式，判断首字母是否是英文字母
					if (sortString.matches("[A-Z]")) {
						sortModel.setSortLetters(sortString.toUpperCase());
					} else {
						sortModel.setSortLetters("#");
					}
					mSortList.add(sortModel);
				}
			}
		}
		return mSortList;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setRetainInstance(true);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacksAndMessages(null);
		XmppService.removeRosterChangelistener(this);
	}

	@Override
	public void rosterChange() {
		refreshUI();
	}
}
